<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderRefund;
use App\Models\BookHomePurchase;
use App\Validate\BookHomeNewBookValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 新书采购清单 (图书馆端)
 * Class NewBookRecom
 * @package app\api\controller
 */
class BookHomeNewBookLibController extends CommonController
{
    private $model = null;
    private $bookHomePurchaseModel = null;
    private $validate = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new BookHomeOrder();
        $this->bookHomePurchaseModel = new BookHomePurchase();
        $this->validate = new BookHomeNewBookValidate();
    }

    /**
     * 所有(新书)采购清单 (图书馆端查看)(只查看线上的)
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param return_manage_id  归还书籍管理员id   不传  或转空  或 0，表示全部
     * @param book_selector  是否套书   不传  或转空  或 0，表示全部  1 是 2 否
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
  //   * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param node   是否借阅成功  0全部 1成功  2 失败
     * @param page  页数，默认为1
     * @param limit  条数，默认显示 10条
     */
    public function purchaseShopList()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(203, '您无权查看书店数据'); //无权限访问
        }

        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $is_return = $this->request->is_return;
        $is_overdue = $this->request->is_overdue;
        $book_selector = $this->request->book_selector;
        $node = $this->request->node;
      //  $way = $this->request->way;
        $settle_state = $this->request->settle_state;
        $pur_manage_id = $this->request->pur_manage_id;
        $return_manage_id = $this->request->return_manage_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'is_return' => $is_return,
            'is_overdue' => $is_overdue,
            'book_selector' => $book_selector,
            'way' => 1,
            'type' => 1, //新书
            'node' => $node,
            'settle_state' => $settle_state,
            'pur_manage_id' => $pur_manage_id,
            'return_manage_id' => $return_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
        ];

        //列表
        $res = $this->bookHomePurchaseModel->lists($param);

        //人次
        $param['select_way'] = 2;
        $user_count = $this->bookHomePurchaseModel->lists($param);

        //总金额
        $param['select_way'] = 3;
        $book_price_count = $this->bookHomePurchaseModel->lists($param);

        $res['book_count'] = $res['total']; //书的统计记录等于总个条数
        $res['user_count'] = $user_count;
        $res['book_price_count'] = $book_price_count;

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');


        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 所有(馆藏书)采购清单 (图书馆端查看)(只查看线上的)
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param return_manage_id  归还书籍管理员id   不传  或转空  或 0，表示全部
     * @param node   是否借阅成功  0全部 1成功  2 失败
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function purchaseLibList()
    {
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $is_return = $this->request->is_return;
        $is_overdue = $this->request->is_overdue;
        $node = $this->request->node;
        $return_manage_id = $this->request->return_manage_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'is_return' => $is_return,
            'is_overdue' => $is_overdue,
            'node' => $node,
            'return_manage_id' => $return_manage_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
        ];
        //列表
        $res = $this->bookHomePurchaseModel->libLists($param);

        //人次
        $param['select_way'] = 2;
        $user_count = $this->bookHomePurchaseModel->libLists($param);

        //总金额
        $param['select_way'] = 3;
        $book_price_count = $this->bookHomePurchaseModel->libLists($param);

        $res['book_count'] = $res['total']; //书的统计记录等于总个条数
        $res['user_count'] = $user_count;
        $res['book_price_count'] = $book_price_count;

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 新书 数据 写入图书馆系统失败后，手动处理
     * @param purchase_ids 采购id  多个用 ， 逗号拼接
     */
    public function disposeSuccess()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('dispose_success')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $purchase_ids = $this->request->purchase_ids;
        $purchase_ids_arr = explode(',', $purchase_ids);
        foreach ($purchase_ids_arr as $key => $val) {
            $res = $this->bookHomePurchaseModel->find($val);
            if ($res['node'] == 2 && $res['is_dispose'] == 2) {
                $res->is_dispose = 1;
                $res->dispose_time = date('Y-m-d H:i:s');
                $res->save();
            }
        }
        return $this->returnApi(200, '处理成功', true);
    }

    /**
     * 计算采购数量及结算状态数量
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
   //  * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param settle_sponsor_manage_id  发起结算的管理员id   不传  或转空  或 0，表示全部
     */
    public function getPurchaseNumber()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(202, '您无权操作此书店'); //无权限访问
        }

        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        //     $settle_state = $this->request->settle_state;
        $book_selector = $this->request->book_selector;
        $way = $this->request->way;
        $pur_manage_id = $this->request->pur_manage_id;
        $settle_sponsor_manage_id = $this->request->settle_sponsor_manage_id;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'book_selector' => $book_selector,
            'way' => $way,
            'type' => 1, //只算新书
            'pur_manage_id' => $pur_manage_id,
            'settle_sponsor_manage_id' => $settle_sponsor_manage_id,
            'shop_all_id' => $shop_all_id,
        ];
        $param['select_way'] = 4;
        $param['settle_state'] = null;
        $data['purchase_number'] = $this->bookHomePurchaseModel->lists($param); //总数量
        $param['settle_state'] = 3;
        $data['unfinal_number'] = $this->bookHomePurchaseModel->lists($param); //未结算数量
        $param['settle_state'] = 2;
        $data['finaling_number'] = $this->bookHomePurchaseModel->lists($param); //结算中数量
        $param['settle_state'] = 1;
        $data['final_number'] = $this->bookHomePurchaseModel->lists($param); //已结算数量


        $param['select_way'] = 3;
        $param['settle_state'] = null;
        $data['purchase_money'] = $this->bookHomePurchaseModel->lists($param); //总金额
        $param['settle_state'] = 3;
        $data['unfinal_money'] = $this->bookHomePurchaseModel->lists($param); //未结算金额
        $param['settle_state'] = 2;
        $data['finaling_money'] = $this->bookHomePurchaseModel->lists($param); //结算中金额
        $param['settle_state'] = 1;
        $data['final_money'] = $this->bookHomePurchaseModel->lists($param); //已结算金额

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 修改采购清单状态为 结算中
     * @param purchase_ids  采购清单id  多个 ，逗号拼接
     */
    public function purchaseStateModify()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('purchase_state_modify')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }

        $purchase_ids = $this->request->purchase_ids;
        $purchase_ids = explode(',', $purchase_ids);
        $res = $this->bookHomePurchaseModel->whereIn('id', $purchase_ids)->get();
        DB::beginTransaction();
        try {
            $ids = [];
            foreach ($res as $key => $val) {
                if ($val['settle_state'] != 3) {
                    continue;
                }
                $ids[] = $val['id'];
            }
            $this->bookHomePurchaseModel->whereIn('id', $ids)->update([
                'settle_state' => 2,
                'settle_sponsor_time' => date('Y-m-d H:i:s'),
                'settle_sponsor_manage_id' => $this->request->manage_id,
            ]);
            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }


    /**
     * 获取采购清单详情
     * @param purchase_id  采购清单id
     */
    public function purchaseDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('purchase_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->bookHomePurchaseModel->detail($this->request->purchase_id);
        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '暂无数据');
    }



    /**
     * 申请退款列表
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param keywords_type  检索条件   0 全部 1 订单号 2 读者证号 3 读者证号姓名 4、收货电话号码
     * @param keywords  检索条件
     * @param shop_id 书店id   不传  或转空  或 0，表示全部
     * @param type	  类型 0、全部 1 新书（默认）   2 馆藏书 （如果type为2，shop_id无效，前端变为不可选状态）
     * @param page  页数默认为 1
     * @param limit  条数 默认 10 条
     */
    public function refundList()
    {
        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type = $this->request->type;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $shop_all_id = $this->getAdminShopIdAll();
        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'type' => $type,
            'page' => $page,
            'limit' => $limit,
            'shop_all_id' => $shop_all_id,
        ];
        $res = $this->model->refundList($param);

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 审核拒绝或无法发货，进行退款操作
     * @param order_id 订单id
     * @param refund_remark 退款备注
     */
    public function refund()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('refund')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //退款成功
        DB::beginTransaction();
        try {
            $bookHomeOrderRefundModel = new BookHomeOrderRefund();
            $res = $bookHomeOrderRefundModel->refund($this->request->order_id, $this->request->refund_remark);
            if ($res !== true) {
                //退款失败
                return $this->returnApi(202, $res);
            }
            return $this->returnApi(200, '退款成功', true);
        } catch (\Exception $e) {
            Log::error('图书到家退款失败：' . $e->getMessage() . $e->getFile() . $e->getLine());

            DB::rollBack();
            return $this->returnApi(202, '退款失败');
        }
    }
}
